package cc.higou.service;

import cc.higou.core.dao.SkuMapper;
import cc.higou.core.pojo.Product;
import cc.higou.core.pojo.Sku;
import cc.higou.core.pojo.SuperPojo;
import cc.higou.core.tools.PageHelper;
import com.github.abel533.entity.Example;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("solrService")
public class SolrServiceImpl implements SolrService {

    @Autowired
    private SolrServer solrServer;
    @Autowired
    private ProductService productService;
    @Autowired
    private SkuMapper skuMapper;


    @Override
    public PageHelper.Page<SuperPojo> findAllFromSolr(String keyword, String sort, Integer pageNum, Integer pageSize, Long brandId, Integer fa, Integer fb) throws SolrServerException {
        //从solr中查询所需要的信息
        List<SuperPojo> al = new ArrayList<>();

        //分页显示
        PageHelper.Page<SuperPojo> page = new PageHelper.Page<>(pageNum, pageSize);

        //创建查询条件
        SolrQuery solrQuery = new SolrQuery("name_ik:" + keyword);

        //设置品牌的条件查询
        if (brandId != null) {
            solrQuery.addFilterQuery("brandId:" + brandId);
        }
        //设置价格区间的排序
        if (fa != null && fb != null) {
            if (fb == -1) {
                solrQuery.addFilterQuery("price:[" + fa + " TO *]");
            } else {
                solrQuery.addFilterQuery("price:[" + fa + " TO " + fb + "]");
            }
        }

        //设置排序
        if (sort != null && sort.trim().length() > 1) {
            SolrQuery.SortClause sortClause = new SolrQuery.SortClause(sort.split(" ")[0], sort.split(" ")[1]);
            solrQuery.setSort(sortClause);
        }
        /**
         * 设置高亮显示
         */
        solrQuery.setHighlight(true);
        solrQuery.setHighlightSimplePre("<font color='red'>");
        solrQuery.setHighlightSimplePost("</font>");
        solrQuery.addHighlightField("name_ik");

        //设置solr分页显示
        solrQuery.setStart(page.getStartRow());
        solrQuery.setRows(page.getPageSize());


        //执行查询获取查询的响应
        QueryResponse response = solrServer.query(solrQuery);
//第一层map的key是文档对象的id，第二层的key为高亮字段，值为这个高亮字段对应的高亮值
        Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();


        //获取结果集
        SolrDocumentList results = response.getResults();

        //总数
        page.setTotal(results.getNumFound());

        //遍历封装
        for (SolrDocument result : results) {
            SuperPojo superPojo = new SuperPojo();
            // 商品id
            String id = (String) result.getFieldValue("id");
            superPojo.setProperty("id", id);

            // 商品名称
            // String name = (String) solrDocument.get("name_ik");
            // superProduct.setProperty("name", name);

            // 取得高亮数据集合中的商品名称
            Map<String, List<String>> map = highlighting.get(id);
            String string = map.get("name_ik").get(0);
            superPojo.setProperty("name", string);

            // 图片地址
            String imgUrl = (String) result.getFieldValue("url");
            superPojo.setProperty("url", imgUrl);

            // 商品最低价格
            Float price = (Float) result.getFieldValue("price");
            superPojo.setProperty("minPrice", price);

            // 品牌id
            Long brandId2 = (Long) result.getFieldValue("brandId");
            superPojo.setProperty("brandId", brandId2);

            // 将万能商品对象添加到集合中
            al.add(superPojo);

        }
        //将结果集放到page中
        page.setResult(al);
        return page;
    }

    @Override
    public void addProduct(String ids) throws SolrServerException, IOException {
        if (ids == null || ids.length() == 0) {
            return;
        }

        String[] split = ids.split(",");
        for (String id : split) {
            //根据id查询商品的信息
            Product product = productService.findProductById(Long.parseLong(id));

            SolrInputDocument document = new SolrInputDocument();
            Long productId = product.getId();
            document.addField("id", productId);
            String imgUrl = product.getImgUrl();
            if (imgUrl != null && imgUrl.length() > 0) {
                String url = imgUrl.split(",")[0];
                document.addField("url", url);
            }
            Long brandId = product.getBrandId();
            document.addField("brandId", brandId);
            String name = product.getName();
            document.addField("name_ik", name);

            //查询sku表中该商品的最低价
            Example example = new Example(Sku.class);
            example.createCriteria().andEqualTo("productId", Long.parseLong(id));
            example.setOrderByClause("price asc");
            PageHelper.startPage(1, 1);
            skuMapper.selectByExample(example);
            PageHelper.Page<Sku> page = PageHelper.endPage();
            Float price = page.getResult().get(0).getPrice();
            document.addField("price", price);

            solrServer.add(document);
            solrServer.commit();
        }
    }
}
